package util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MapUtil {
	
	/**
	 * 将request获取的参数转化为Map<String,String>形式
	 * @param params request.getParameters()
	 * @return 
	 */
	public static Map mapToStringMap(Map params) {
		Map<String,String> returnParams = new HashMap<String,String>();
		
		Iterator it = params.keySet().iterator();
		while(it.hasNext()) {
			String key = it.next().toString();
			Object[] value = (Object[])params.get(key);
			String valueToString = "";
			if(null != value && value.length > 0 ) {
				valueToString = value[0].toString();
				
			}
			returnParams.put(key, valueToString);
		}
		return returnParams;
	}
	
	/**
	 * 将request获取的参数转化为Map<String,String>或Map<String,List>形式
	 * 需转化为List的参数名以_list结尾，否则转化为String
	 * @param params request.getParameters()
	 * @return 
	 */
	public static Map mapToListMap(Map params) {
		Map returnParams = new HashMap();
		
		Iterator it = params.keySet().iterator();
		while(it.hasNext()) {
			String key = it.next().toString();
			Object[] value = (Object[])params.get(key);
			List<String> valueToList = new ArrayList<String>(); 
			String valueToString = "";
			if(key.endsWith("_list")) {
				if(null != value && value.length > 0 ) {
					int length = value.length;
					for(int i=0; i<length; i++) {
						valueToList.add(value[i].toString());
					}
				}
				returnParams.put(key, valueToList);
			} else {
				if(null != value && value.length > 0 ) {
					valueToString = value[0].toString();
				}
				returnParams.put(key, valueToString);
			}
			
			
		}
		return returnParams;
	}
}
